package cn.fl.capital.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.dto.CapFundDTO;
import cn.fl.capital.service.ICapFundService;
import cn.fl.capital.vo.CapFundVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
* @Description:    流程中操作资金controller
* @Author:         liurong
* @CreateDate:     2019/4/25 9:41
* @Version:        1.0
*/
@Controller
@RequestMapping("/capital/capFund/flow")
public class CapFundInFlowController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(CapFundInFlowController.class);

    @Autowired
    private IPrjPrdDtlService prjPrdDtlService;
    @Autowired
    private ICapFundService capFundService;

    /**
     * 初始化页面数据
     * @param request
     * @return
     */
    @RequestMapping(value = "/initPageFlowData.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO initFundFlowData(HttpServletRequest request) {
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        String paySchId = request.getParameter("paySchId");
        JSONObject dataJson = new JSONObject();
        try {
            if (StringUtils.isEmpty(paySchId)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "支付表ID不能为空！");
            }

            //结清时间
            PrjPrdDtlQueryCondition dtlQueryCondition = new PrjPrdDtlQueryCondition();
            dtlQueryCondition.setPaySchId(Long.parseLong(paySchId));
            List<PrjPrdDtlVO> prdDtlVOList = this.prjPrdDtlService.selectList(dtlQueryCondition);
            String stlDt = "";
            Long prjPrdDtlId = null;
            if (CollectionUtils.isNotEmpty(prdDtlVOList)) {
                PrjPrdDtlVO prjPrdDtlVO = prdDtlVOList.get(0);
                if (null != prjPrdDtlVO.getStlDt()) {
                    stlDt = DateUtils.formatDateToString(prjPrdDtlVO.getStlDt(), DateUtils.YYYY_MM_DD);
                }
                prjPrdDtlId = prjPrdDtlVO.getId();
            }
            dataJson.put("stlDt", stlDt);
            dataJson.put("prjPrdDtlId", prjPrdDtlId);

            resultVO.setData(dataJson);
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "initPageFlowData", "初始化页面数据异常", e);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "initPageFlowData", "初始化页面数据异常", e);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo("查询数据失败！");
        }
        return resultVO;
    }

    /**
     * 选择来款绑定流程
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toChooseFund.do", method = {RequestMethod.GET})
    public ModelAndView toChooseFund(HttpServletRequest request, HttpServletResponse response){
        BaseLogUtils.info(logger, "toChooseFund", "到选择来款绑定流程页面.", CurrentThreadContext.getCurrentUserName());
        String type = request.getParameter("type");
        //业务类型 1.结清 2.添加风险保证金
        String bizTypCd = request.getParameter("bizTypCd");
        String relationPayId = request.getParameter("relationPayId");
        if (StringUtils.isEmpty(relationPayId)) {
            BaseLogUtils.info(logger, "toChooseFund", "到选择来款绑定流程页面失败，参数不全.", CurrentThreadContext.getCurrentUserName());
            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600, "请求参数不完整");
        }
        ModelAndView mav = new ModelAndView("capital/capFund/chooseFundInFlow");
        mav.addObject("relationPayId", relationPayId);
        mav.addObject("type",type);
        mav.addObject("bizTypCd",bizTypCd);
        return mav;
    }

    /**
     * 母资金拆分子资金
     * @param request
     * @return
     */
    @RequestMapping(value = "/splitFund.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO splitFund(HttpServletRequest request) {
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            String ids = request.getParameter("ids");
            String relationPayId = request.getParameter("relationPayId");
            String cstId = request.getParameter("cstId");
            String cstNm = request.getParameter("cstNm");
            if (StringUtils.isEmpty(ids)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "资金ID不能为空！");
            }
            if (StringUtils.isEmpty(relationPayId)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "关联付款ID不能为空！");
            }

            List<Long> idsList = new ArrayList<>();
            JSONArray idsArray = JSONArray.parseArray(ids);
            for (Object object : idsArray) {
                idsList.add(Long.valueOf(object.toString()));
            }
            if (CollectionUtils.isEmpty(idsList)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "资金ID不能为空！");
            }
            CapFundDTO capFundDTO = new CapFundDTO();
            capFundDTO.setIdList(idsList);
            capFundDTO.setRelationPayId(Long.valueOf(relationPayId));
            if (StringUtils.isNotEmpty(cstId)) {
                capFundDTO.setCstId(Long.valueOf(cstId));
            }
            if (StringUtils.isNotEmpty(cstNm)) {
                capFundDTO.setCstNm(cstNm);
            }
            boolean result = capFundService.addChildFundFromParentFund(capFundDTO);
            if (!result) {
                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultVO.setInfo("添加资金失败！");
            }
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "splitFund", "拆分子资金异常", e);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "splitFund", "拆分子资金异常", e);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo("添加资金失败！");
        }
        return resultVO;
    }

    /**
     * 删除子资金
     * @param request
     * @return
     */
    @RequestMapping(value = "/delChildFund.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO delChildFund(HttpServletRequest request) {
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            String childFundId = request.getParameter("id");
            if (StringUtils.isEmpty(childFundId)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "资金ID不能为空！");
            }

            boolean result = capFundService.removeChildFund(Long.parseLong(childFundId));
            if (!result) {
                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultVO.setInfo("删除资金失败！");
            }
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "delChildFund", "删除子资金异常", e);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "delChildFund", "删除子资金异常", e);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo("删除资金失败！");
        }
        return resultVO;
    }

    /**
     * 修改子资金
     * @param request
     * @return
     */
    @RequestMapping(value = "/modifyChildFund.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO modifyChildFund(HttpServletRequest request) {
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        try {
            String childFundId = request.getParameter("id");
            if (StringUtils.isEmpty(childFundId)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "资金ID不能为空！");
            }
            String availAmtStr = request.getParameter("availAmt");
            if (StringUtils.isEmpty(availAmtStr)) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "可用金额不能为空！");
            }
            Long availAmt = null;
            try {
                availAmt = DecimalUtils.convertYuanToFen(Double.parseDouble(availAmtStr));
            } catch (NumberFormatException e) {
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "可用金额数据类型转换错误！");
            }
            CapFundVO capFundVO = new CapFundVO();
            capFundVO.setId(Long.parseLong(childFundId));
            capFundVO.setAvailableAmount(availAmt);
            boolean result = capFundService.modifyChildFund(capFundVO);
            if (!result) {
                resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                resultVO.setInfo("修改资金失败！");
            }
        } catch (BaseException e) {
            BaseLogUtils.error(logger, "modifyChildFund", "修改子资金异常", e);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(e.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, "modifyChildFund", "修改子资金异常", e);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo("修改资金失败！");
        }
        return resultVO;
    }

}
